package com.tsinghuabigdata.edu.ddmath.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.tsinghuabigdata.edu.ddmath.util.AppLog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by HP on 2016/10/20.
 */
public class LatexWebView extends WebView {

    public LatexWebView(Context context) {
        super(context);
    }

    public LatexWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LatexWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public LatexWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public LatexWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean
            privateBrowsing) {
        super(context, attrs, defStyleAttr, privateBrowsing);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        WebSettings webSettings = getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);

        webSettings.setSupportZoom(false);
        //webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);

        // Enable plugin
        webSettings.setPluginState(WebSettings.PluginState.ON);
        //webSettings.setBlockNetworkImage(true);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            removeJavascriptInterface("searchBoxJavaBridge_");
        }
        removeJavascriptInterface("accessibility");
        removeJavascriptInterface("accessibilityTraversal");

        setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    AppLog.i("load latex text success.");
                }
            }
        });

        loadUrl("file:///android_asset/mathjax.html");

        setOnLongClickListener(new WebView.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
    }

    public void setLatexText(String latexText) {

        String js = "javascript:window.startMathJax('" + doubleEscapeTeX( latexText ) + "');";
        loadUrl(js);

//        latexText = latexText.replaceAll("\\\\", "\\\\\\\\");
//        String js = "javascript:setText(\"" + latexText + "\")";
//        loadUrl(js);
    }
    private String doubleEscapeTeX(String s) {
        String t="";
        for (int x=0; x < s.length(); x++) {
            if (s.charAt(x) == '\'') t += '\\';
            //else if (s.charAt(x) == '$') t += ' ';
            else if (s.charAt(x) != '\n') t += s.charAt(x);
            if (s.charAt(x) == '\\') t += "\\";
        }

//        Pattern pattern = Pattern.compile("\\$.*?\\$");
//        Matcher matcher;
//        matcher = pattern.matcher( t );
//        while (matcher.find()) {
//            String latexstr = matcher.group();
//            t = t.replace(latexstr, "\\\\[" + latexstr.substring(1, latexstr.length() - 1)+ "\\\\]" );
//            matcher = pattern.matcher(t);
//        }
        return t;
    }


    public void putImage(String imageSrcArray) {
        String js = "javascript:putImage(\"" + imageSrcArray + "\")";
        loadUrl(js);
    }

}
